﻿using RFID.Model;
using RFID.VModel;
using System;
using System.Collections.Generic;
using System.Linq;

namespace RFID.BLL
{
    public class RichInfoBLL
    {
        /// <summary>
        /// 查询充值记录
        /// </summary>
        /// <param name="key">卡号或学号</param>
        /// <returns>一卡通列表</returns>
        public static List<RichInfoView> Select(string key = "")
        {
            using (RFIDDataContext db = new RFIDDataContext())
            {
                return db.RichInfo.Where(p => string.IsNullOrEmpty(key) || p.RId == key || p.CardInfo.Sid.ToString() == key).OrderByDescending(p => p.Date).Select(p => new RichInfoView { 充值编号 = p.Id, 卡号 = p.RId, 充值余额 = p.Rich, Date = p.Date }).ToList();
            }
        }

        /// <summary>
        /// 添加充值记录
        /// </summary>
        /// <param name="rich">充值记录</param>
        /// <returns></returns>
        public static OperateResult<bool> AddRich(RichInfo rich)
        {
            using (RFIDDataContext db = new RFIDDataContext())
            {
                var card = db.CardInfo.FirstOrDefault(p => p.Id == rich.RId);
                var result = CardInfoBLL.Validate(card);
                if (!result.Status)
                    return result;

                try
                {
                    rich.Date = DateTime.Now;
                    card.Rich += rich.Rich;
                    card.RichInfo.Add(rich);
                    db.SubmitChanges();
                    return OperateResult<bool>.Succeeded(true);
                }
                catch (Exception ex)
                {
                    return OperateResult<bool>.Failed(ex);
                }
            }
        }
    }
}
